import { NextRequest, NextResponse } from 'next/server';
import { query } from '@/lib/mysql';
import { getCurrentUser } from '@/lib/auth';

export async function GET(request: NextRequest) {
  try {
    // 验证用户身份
    const user = getCurrentUser();
    if (!user || user.role !== 'admin') {
      return NextResponse.json(
        { success: false, error: '需要管理员权限' },
        { status: 403 }
      );
    }

    // 获取用户列表
    const users = await query(
      `SELECT 
        u.id,
        u.username,
        u.email,
        u.display_name as displayName,
        u.role,
        u.is_active as isActive,
        u.created_at as createdAt,
        u.last_login_at as lastLoginAt,
        up.school,
        up.grade,
        COALESCE(stats.totalSessions, 0) as totalSessions,
        COALESCE(stats.averageAccuracy, 0) as averageAccuracy
      FROM users u
      LEFT JOIN user_profiles up ON u.id = up.user_id
      LEFT JOIN (
        SELECT 
          user_id,
          COUNT(*) as totalSessions,
          AVG(CASE WHEN question_count > 0 THEN (correct_count / question_count * 100) ELSE 0 END) as averageAccuracy
        FROM practice_sessions
        GROUP BY user_id
      ) stats ON u.id = stats.user_id
      ORDER BY u.created_at DESC`
    );

    return NextResponse.json({
      success: true,
      data: users
    });

  } catch (error) {
    console.error('获取用户列表错误:', error);
    return NextResponse.json(
      { 
        success: false, 
        error: error instanceof Error ? error.message : '获取用户列表失败' 
      },
      { status: 500 }
    );
  }
}

